package com.itbaizhan.rediswebdemo.service;

import com.alibaba.fastjson.JSON;
import com.itbaizhan.rediswebdemo.entity.GoodsEntity;
import com.itbaizhan.rediswebdemo.repository.GoodsRepository;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Optional;

/*商品的业务层，业务层调用持久层（持久层控制数据库）*/

/*用jmemter测度吞吐量
启动Jmeter工具
D:\apache-jmeter-5.4.3\bin\jmeter.bat文件双击运行。
* 没有redis缓存  10000并发   427qps(吞吐量)
* redis缓存  10000并发   828qps*/
@Service
public class GoodsService {

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private StringRedisTemplate redisTemplate;
    /*根据id查询商品信息*/
    public GoodsEntity getById(Long id){

        //查询缓存
        String goodsString = redisTemplate.opsForValue().get("goods:"+id);
        //判断有没有缓存
        if(StringUtils.isEmpty(goodsString)){
            //从数据库中查询
            Optional<GoodsEntity> goodsEntity = goodsRepository.findById(id);
            /*isPresent()  boolean
             * 商品有时，返回商品*/
            if(goodsEntity.isPresent()){
                GoodsEntity goodsEntity1 = goodsEntity.get();

                //把对象转为json字符串 然后添加到缓存
                // {"id":1,"goodsName":"java","orderId":"1","goodsNum":12,"price":1200.0}
                String s = JSON.toJSONString(goodsEntity1);

                //添加缓存
                redisTemplate.opsForValue().set("goods:"+id,s);
                return goodsEntity1;
            }
        }else {
            //如果有缓存   字符串转为对象
            GoodsEntity goodsEntity2 = JSON.parseObject(goodsString, GoodsEntity.class);
            return goodsEntity2;

        }

        return null;
    }
}
